﻿#region

using System.Collections;
using System.Reflection;

#endregion

namespace Vin.Tool.Attributes;

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class InjectAttribute : Attribute
{
    public string? Key { get; set; }

    public InjectAttribute()
    {
    }

    public InjectAttribute(string key)
    {
        this.Key = key;
    }
}

public class InjectModel
{
    public InjectAttribute InjectAttribute { get; set; } = null!;

    public Type Type { get; set; } = null!;

    public bool IsList { get; set; }

    public bool IsArray { get; set; }

    public object? TypeModel { get; set; }

    /// <summary>
    /// 设置列表值
    /// </summary>
    /// <param name="instance"></param>
    /// <param name="value"></param>
    public void SetListValue(object instance, object? value)
    {
        var listType = typeof(List<>).MakeGenericType(this.Type.GetGenericArguments()[0]);
        var list = (IList?)Activator.CreateInstance(listType);
        foreach (var item in (value as IEnumerable<object>)!)
        {
            list!.Add(item);
        }

        SetDefaultValue(instance, list);
    }

    /// <summary>
    /// 设置默认值
    /// </summary>
    /// <param name="instance"></param>
    /// <param name="value"></param>
    public void SetDefaultValue(object instance, object? value)
    {
        switch (this.TypeModel)
        {
            case FieldInfo fieldInfo:
                fieldInfo.SetValue(instance, value);
                break;
            case PropertyInfo propertyInfo:
                propertyInfo.SetValue(instance, value);
                break;
        }
    }
}